
<template>
	<div class="min-h-screen bg-slate-50">
		<!-- 左侧导航 -->
		<div class="fixed left-0 top-0 h-full w-64 bg-white shadow-lg backdrop-blur-sm z-10 transition-all duration-300"
			:class="{ '-translate-x-full': isSidebarHidden || window.innerWidth < 1024 }">
			<!-- 搜索框 -->
			<div class="p-4">
				<div class="relative">
					<input type="text" v-model="searchQuery" @keyup.enter="searchHistory" placeholder="搜索历史对话..."
						class="w-full pl-10 pr-4 py-2.5 bg-slate-50/50 rounded-xl text-sm border-none focus:ring-2 focus:ring-blue-100/50 transition-all">
					<i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
				</div>
			</div>
			<!-- 对话历史列表 -->
			<div class="overflow-y-auto h-[calc(100vh-180px)]">
				<div v-for="chat in chatHistory" :key="chat.id" :class="{'bg-blue-50': chat.id === currentChatId}"
					@click="currentChatId = chat.id"
					class="group px-2 py-3 hover:bg-slate-50 cursor-pointer transition-colors border-b border-slate-100 last:border-b-0">
					<div class="flex items-start justify-between gap-1">
						<div class="flex flex-col min-w-0">
							<span class="text-sm text-gray-700 font-medium mb-1 truncate">{{ chat.title }}</span>
							<span class="text-xs text-gray-400">{{ chat.time }}</span>
						</div>
						<button @click.stop="deleteChat(chat.id)"
							class="!rounded-button shrink-0 w-6 h-6 flex items-center justify-center text-gray-400 hover:text-red-500 hover:bg-gray-100 transition-all">
							<i class="fas fa-trash-alt text-xs"></i>
						</button>
					</div>
				</div>
			</div>
			<div class="absolute -right-10 top-4">
				<button @click="toggleSidebar"
					class="!rounded-button w-8 h-8 flex items-center justify-center text-gray-400 hover:text-gray-600 bg-white transition-all">
					<i class="fas" :class="isSidebarHidden ? 'fa-chevron-right' : 'fa-chevron-left'"></i>
				</button>
			</div>
		</div>
		<!-- 主聊天区域 -->
		<div class="ml-64 h-screen flex flex-col bg-slate-50/50"
			:class="{ 'ml-0': isSidebarHidden || window.innerWidth < 1024 }">
			<!-- 顶部栏 -->
			<div
				class="min-h-32 py-6 md:py-4 border-b bg-white backdrop-blur-sm flex items-center justify-between px-4 md:px-16 relative shadow-sm">
				<div class="absolute top-4 right-4 flex gap-2">
					<button @click="createNewChat"
						class="!rounded-button w-8 h-8 flex items-center justify-center text-slate-500 hover:text-slate-700 bg-slate-100 hover:bg-slate-200 transition-all">
						<i class="fas fa-plus text-sm"></i>
					</button>
					<button @click="clearCurrentChat"
						class="!rounded-button w-8 h-8 flex items-center justify-center text-gray-500 hover:text-gray-700 bg-gray-50 hover:bg-gray-100 transition-all">
						<i class="fas fa-trash-alt text-sm"></i>
					</button>
					<button @click="openSettings"
						class="!rounded-button w-8 h-8 flex items-center justify-center text-gray-500 hover:text-gray-700 bg-gray-50 hover:bg-gray-100 transition-all">
						<i class="fas fa-cog text-sm"></i>
					</button>
				</div>
				<div class="flex-1 flex flex-col md:flex-row items-center justify-center gap-4 md:gap-6">
					<div class="w-16 h-16 rounded-2xl flex items-center justify-center shrink-0">
						<img src="https://static.jbolt.cn/website/jboltai_logo_icon.png" alt="Logo"
							class="w-full h-full object-contain">
					</div>
					<div class="flex flex-col items-center md:items-start">
						<h2
							class="text-2xl md:text-3xl font-bold bg-gradient-to-r from-[#4f46e5] via-[#4338ca] to-[#3730a3] bg-clip-text text-transparent tracking-wider text-center md:text-left whitespace-nowrap">
							JBoltAI应用客户端测试Demo</h2>
						<div class="flex items-center gap-4 mt-2">
							<p class="text-gray-500 font-medium whitespace-nowrap">智能应用开发</p>
							<div class="w-1.5 h-1.5 rounded-full bg-gray-300"></div>
							<p class="text-gray-500 font-medium whitespace-nowrap">AI 数智化转型</p>
							<div class="w-1.5 h-1.5 rounded-full bg-gray-300"></div>
							<p class="text-gray-500 font-medium whitespace-nowrap">企业级解决方案</p>
						</div>
					</div>
				</div>
			</div>
			<!-- 对话内容区 -->
			<div ref="chatContainer" class="flex-1 overflow-y-auto p-6 bg-gradient-to-b from-slate-50 to-white">
				<div v-for="message in messages" :key="message.id" class="mb-6 animate-fade-in"
					:data-message-id="message.id">
					<div :class="message.type === 'user' ? 'flex justify-end' : 'flex justify-start'">
						<div :class="[
'max-w-[85%] px-5 py-3.5 shadow-sm transform transition-all duration-200 hover:shadow-md group',
message.type === 'user' ? 'bg-gradient-to-br from-[#6366f1] to-[#818cf8] text-white backdrop-blur-sm rounded-l-2xl rounded-br-2xl' : 'bg-white text-slate-700 border border-slate-100/80 rounded-tr-2xl rounded-b-2xl'
]">
							<div class="text-base leading-relaxed whitespace-pre-wrap break-words">{{ message.content }}
							</div>
							<div v-if="message.type === 'ai'" class="mt-2 pt-2 border-t border-slate-100">
								<div class="flex justify-between items-center text-xs text-slate-400">
									<span>{{ message.time || '2024-01-22 15:30' }}</span>
									<span>AI生成，仅供参考</span>
								</div>
								<div class="flex gap-2 mt-1.5">
									<button
										class="!rounded-button p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-50">
										<i class="fas fa-copy text-xs"></i>
									</button>
									<button
										class="!rounded-button p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-50">
										<i class="fas fa-redo-alt text-xs"></i>
									</button>
									<button
										class="!rounded-button p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-50">
										<i class="fas fa-volume-up text-xs"></i>
									</button>
									<button @click.stop="deleteMessages(message.id)"
										class="!rounded-button p-1.5 text-slate-400 hover:text-red-500 hover:bg-slate-50">
										<i class="fas fa-trash-alt text-xs"></i>
									</button>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<!-- 输入区域 -->
			<div class="border-t bg-white backdrop-blur-lg p-3 sticky bottom-0 shadow-[0_-2px_10px_rgba(0,0,0,0.03)]">
				<div class="w-full mx-auto">
					<div class="flex items-center gap-2">
						<div class="flex-1 bg-slate-50/70 rounded-2xl shadow-sm hover:shadow-md transition-all">
							<div class="flex flex-col">
								<!-- 文件预览区域 -->
								<div v-if="selectedFiles.length > 0" class="px-4 py-2 border-t">
									<div class="text-sm text-gray-500 mb-2">已选择的文件：</div>
									<div class="flex flex-wrap gap-2">
										<div v-for="(file, index) in selectedFiles" :key="index"
											class="flex items-center bg-gray-50 rounded-lg px-3 py-2 text-sm">
											<i class="fas fa-file mr-2 text-blue-500"></i>
											<span class="truncate max-w-[200px]">{{ file.name }}</span>
											<button @click="removeFile(index)"
												class="ml-2 text-gray-400 hover:text-gray-600">
												<i class="fas fa-times"></i>
											</button>
										</div>
									</div>
								</div>
								<!-- 图片预览区域 -->
								<div v-if="selectedImages.length > 0" class="px-4 py-2 border-t">
									<div class="text-sm text-gray-500 mb-2">已选择的图片：</div>
									<div class="flex flex-wrap gap-2">
										<div v-for="(image, index) in selectedImagePreviews" :key="index"
											class="relative group w-20 h-20 rounded-lg overflow-hidden">
											<img :src="image" class="w-full h-full object-cover">
											<button @click="removeImage(index)"
												class="absolute top-1 right-1 w-6 h-6 rounded-full bg-black bg-opacity-50 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
												<i class="fas fa-times text-sm"></i>
											</button>
										</div>
									</div>
								</div>
								<!-- 输入区域 -->
								<div class="flex">
									<div class="flex-none flex items-end p-2 gap-2">
										<input type="file" ref="fileInput" @change="handleFileSelect" class="hidden"
											multiple accept=".pdf,.doc,.docx,.txt">
										<input type="file" ref="imageInput" @change="handleImageSelect" class="hidden"
											multiple accept="image/*">
										<button @click="triggerImageUpload"
											class="!rounded-button h-[34px] w-[34px] rounded-full flex items-center justify-center text-gray-500 hover:bg-gray-100 transition-colors">
											<i class="fas fa-image text-lg"></i>
										</button>
										<button @click="triggerFileUpload"
											class="!rounded-button h-[34px] w-[34px] rounded-full flex items-center justify-center text-gray-500 hover:bg-gray-100 transition-colors">
											<i class="fas fa-paperclip text-lg"></i>
										</button>
									</div>
									<div class="flex-1 flex items-center">
										<textarea v-model="inputMessage" rows="1" placeholder="输入你的问题..."
											class="w-full p-2 bg-transparent border-none resize-none text-sm leading-relaxed min-h-[34px] max-h-[300px] transition-all duration-200"
											@keydown.enter.prevent="handleEnterPress" @input="autoGrow"
											@keyup="autoGrow" @keydown="autoGrow" ref="textarea">
</textarea>
									</div>
									<div class="flex-none flex items-end p-2">
										<button @click="sendMessage"
											class="!rounded-button h-[34px] w-[34px] rounded-full flex items-center justify-center transition-colors whitespace-nowrap"
											:class="inputMessage.trim() ? 'text-[#4f46e5] hover:text-[#4338ca] hover:bg-[#4f46e5]/5' : 'text-gray-500 hover:bg-gray-100'">
											<i class="fas fa-paper-plane text-lg"></i>
										</button>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 设置弹窗 -->
		<div v-if="showSettings" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
			<div class="bg-white/98 backdrop-blur-md rounded-2xl w-[520px] p-8 shadow-2xl">
				<div class="flex justify-between items-center mb-6">
					<h3 class="text-2xl font-bold text-slate-800">对话参数设置</h3>
					<button @click="closeSettings" class="text-gray-400 hover:text-gray-600">
						<i class="fas fa-times"></i>
					</button>
				</div>
				<div class="space-y-6">
					<div>
						<label class="block text-sm font-semibold text-slate-700 mb-2">温度（Temperature）</label>
						<input type="range" v-model="temperature" min="0" max="100" class="w-full">
						<div class="text-sm text-gray-500 mt-1">当前值：{{ temperature }}%（值越高，回答越具有创造性）</div>
					</div>
					<div>
						<label class="block text-sm font-semibold text-slate-700 mb-2">最大 Tokens</label>
						<input type="range" v-model="maxTokens" min="100" max="4000" class="w-full">
						<div class="text-sm text-gray-500 mt-1">当前值：{{ maxTokens }}（控制回答的最大长度）</div>
					</div>
					<div>
						<label class="block text-sm font-semibold text-slate-700 mb-2">Top P</label>
						<input type="range" v-model="topP" min="0" max="100" class="w-full">
						<div class="text-sm text-gray-500 mt-1">当前值：{{ topP }}%（控制输出的新颖程度）</div>
					</div>
					<div>
						<label class="block text-sm font-semibold text-slate-700 mb-2">Top K</label>
						<input type="range" v-model="topK" min="1" max="100" class="w-full">
						<div class="text-sm text-gray-500 mt-1">当前值：{{ topK }}（限制每次选择的候选词数）</div>
					</div>
					<div>
						<label class="block text-sm font-semibold text-slate-700 mb-2">保持上下文</label>
						<div class="mt-2">
							<label class="inline-flex items-center cursor-pointer">
								<input type="checkbox" v-model="keepContext" class="sr-only peer">
								<div
									class="relative w-11 h-6 bg-slate-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#4f46e5]">
								</div>
								<span class="ml-3 text-sm text-gray-600">启用多轮对话记忆</span>
							</label>
						</div>
					</div>
				</div>
				<div class="flex justify-end space-x-4 mt-6">
					<button @click="closeSettings"
						class="!rounded-button px-6 py-2.5 text-gray-600 hover:bg-gray-100 transition-colors whitespace-nowrap text-sm font-medium">
						取消
					</button>
					<button @click="saveSettings"
						class="!rounded-button px-6 py-2.5 bg-[#4f46e5] text-white hover:bg-[#4338ca] transition-colors whitespace-nowrap text-sm font-medium">
						确认
					</button>
				</div>
			</div>
		</div>
	</div>
</template>
<script lang="ts" setup>
	import { ref, onMounted, nextTick, onBeforeMount } from 'vue';
	// 文件上传相关的响应式变量
	const fileInput = ref<HTMLInputElement | null>(null);
	const imageInput = ref<HTMLInputElement | null>(null);
	const selectedFiles = ref<File[]>([]);
	const selectedImages = ref<File[]>([]);
	const selectedImagePreviews = ref<string[]>([]);
	// 触发文件选择
	const triggerFileUpload = () => {
		fileInput.value?.click();
	};
	// 触发图片选择
	const triggerImageUpload = () => {
		imageInput.value?.click();
	};
	// 处理文件选择
	const handleFileSelect = (event : Event) => {
		const input = event.target as HTMLInputElement;
		if (input.files) {
			const files = Array.from(input.files);
			selectedFiles.value.push(...files);
		}
		input.value = ''; // 清空input使得相同文件可以重复选择
	};
	// 处理图片选择
	const handleImageSelect = (event : Event) => {
		const input = event.target as HTMLInputElement;
		if (input.files) {
			const files = Array.from(input.files);
			selectedImages.value.push(...files);
			// 生成预览URL
			files.forEach(file => {
				const reader = new FileReader();
				reader.onload = (e) => {
					if (typeof e.target?.result === 'string') {
						selectedImagePreviews.value.push(e.target.result);
					}
				};
				reader.readAsDataURL(file);
			});
		}
		input.value = ''; // 清空input使得相同文件可以重复选择
	};
	// 移除文件
	const removeFile = (index : number) => {
		selectedFiles.value.splice(index, 1);
	};
	// 移除图片
	const removeImage = (index : number) => {
		selectedImages.value.splice(index, 1);
		selectedImagePreviews.value.splice(index, 1);
	};
	const isSidebarHidden = ref(false);
	const window = ref(globalThis.window);
	// 监听窗口大小变化
	const handleResize = () => {
		isSidebarHidden.value = window.value.innerWidth < 1024;
	};
	onBeforeMount(() => {
		// 初始化时检查窗口大小
		handleResize();
		// 添加窗口大小变化监听器
		window.value.addEventListener('resize', handleResize);
	});
	const showSettings = ref(false);
	const inputMessage = ref('');
	const textarea = ref<HTMLTextAreaElement | null>(null);
	const handleEnterPress = (e : KeyboardEvent) => {
		if (e.shiftKey) {
			e.preventDefault();
			const start = e.target.selectionStart;
			const end = e.target.selectionEnd;
			inputMessage.value = inputMessage.value.substring(0, start) + '\n' + inputMessage.value.substring(end);
			nextTick(() => {
				e.target.selectionStart = e.target.selectionEnd = start + 1;
			});
			autoGrow();
		} else {
			sendMessage();
		}
	};
	const autoGrow = () => {
		if (textarea.value) {
			// 先将高度设为 auto，使得 scrollHeight 能正确计算
			textarea.value.style.height = 'auto';
			// 计算新高度，限制在 34px 到 300px 之间
			const newHeight = Math.max(34, Math.min(textarea.value.scrollHeight, 300));
			textarea.value.style.height = `${newHeight}px`;
		}
	};
	const temperature = ref(70);
	const maxTokens = ref(2000);
	const topP = ref(70);
	const topK = ref(50);
	const keepContext = ref(true);
	const currentChatId = ref(1);
	const chatContainer = ref<HTMLElement | null>(null);
	const searchQuery = ref('');
	const originalChatHistory = [
		{ id: 1, title: '探讨人工智能的未来发展', time: '14:30' },
		{ id: 2, title: '关于机器学习的技术探讨', time: '昨天' },
		{ id: 3, title: '自然语言处理的应用场景', time: '周二' },
		{ id: 4, title: '深度学习模型优化方案', time: '上周' },
		{ id: 5, title: '智能助手的商业价值分析', time: '2024/1/15' },
	];
	const chatHistory = ref([...originalChatHistory]);
	const deleteChat = (id : number) => {
		chatHistory.value = chatHistory.value.filter(chat => chat.id !== id);
		if (currentChatId.value === id) {
			currentChatId.value = chatHistory.value[0]?.id || 0;
		}
	};
	const createNewChat = () => {
		const newId = Math.max(...chatHistory.value.map(chat => chat.id), 0) + 1;
		const newChat = {
			id: newId,
			title: '新的对话',
			time: new Date().toLocaleTimeString()
		};
		chatHistory.value.unshift(newChat);
		currentChatId.value = newId;
		messages.value = [{
			id: 1,
			type: 'ai',
			content: '欢迎开始新的对话！我是你的智能助手，请问有什么可以帮你的？'
		}];
	};
	const clearCurrentChat = () => {
		messages.value = [{
			id: 1,
			type: 'ai',
			content: '对话已清空。请问有什么可以帮你的？'
		}];
	};
	const searchHistory = () => {
		if (!searchQuery.value.trim()) {
			chatHistory.value = originalChatHistory;
			return;
		}
		const query = searchQuery.value.toLowerCase();
		chatHistory.value = originalChatHistory.filter(chat =>
			chat.title.toLowerCase().includes(query)
		);
	};
	const messages = ref([
		{
			id: 1,
			type: 'ai',
			content: '欢迎使用 JBoltAI！我是你的智能助手，很高兴为你服务。我可以帮你了解 JBoltAI 的产品功能，回答技术问题，或者协助你进行开发工作。'
		},
		{ id: 2, type: 'user', content: '请介绍一下 JBoltAI 的主要功能。' },
		{
			id: 3,
			type: 'ai',
			content: 'JBoltAI 是一个强大的智能应用开发平台，主要功能包括：1. 零代码智能应用构建，通过可视化界面快速创建AI应用；2. 支持多种大语言模型接入，包括 GPT、文心一言等；3. 提供丰富的行业模板和场景方案；4. 完整的开发工具链和API支持；5. 企业级的安全性和可扩展性保障。'
		},
		{ id: 4, type: 'user', content: 'JBoltAI 如何帮助企业实现数智化转型？' },
		{
			id: 5,
			type: 'ai',
			content: 'JBoltAI 通过以下方式助力企业数智化转型：1. 智能客服系统：提供 7x24 小时智能服务，提升客户满意度；2. 知识库管理：自动构建和维护企业知识图谱；3. 流程自动化：利用 AI 技术优化业务流程；4. 数据分析：提供深度的数据洞察和决策支持；5. 定制化解决方案：根据企业特定需求提供个性化AI应用开发服务。'
		},
	]);
	const toggleSidebar = () => {
		isSidebarHidden.value = !isSidebarHidden.value;
	};
	const openSettings = () => {
		showSettings.value = true;
	};
	const closeSettings = () => {
		showSettings.value = false;
	};
	const saveSettings = () => {
		showSettings.value = false;
		// 保存所有设置参数
		const settings = {
			temperature: temperature.value,
			maxTokens: maxTokens.value,
			topP: topP.value,
			topK: topK.value,
			keepContext: keepContext.value
		};
		console.log('保存的设置:', settings);
		// 这里可以添加将设置保存到后端的逻辑
	};
	const deleteMessages = (messageId : number) => {
		const index = messages.value.findIndex(m => m.id === messageId);
		if (index > 0) {
			// 找到要删除的AI回答和对应的用户提问
			const elementsToDelete = [index];
			if (messages.value[index - 1].type === 'user') {
				elementsToDelete.unshift(index - 1);
			}

			// 为要删除的元素添加淡出动画类
			elementsToDelete.forEach(idx => {
				const messageEl = document.querySelector(`[data-message-id="${messages.value[idx].id}"]`);
				if (messageEl) {
					messageEl.classList.add('animate-fade-out');
				}
			});

			// 等待动画完成后删除消息
			setTimeout(() => {
				messages.value = messages.value.filter((_, idx) => !elementsToDelete.includes(idx));
			}, 300);
		}
	};

	const sendMessage = () => {
		if (!inputMessage.value.trim()) return;
		messages.value.push({
			id: Date.now(),
			type: 'user',
			content: inputMessage.value
		});
		// 模拟AI回复
		setTimeout(() => {
			messages.value.push({
				id: Date.now() + 1,
				type: 'ai',
				content: '我已经收到你的消息，正在思考如何回答...'
			});
			scrollToBottom();
		}, 500);
		inputMessage.value = '';
		scrollToBottom();
	};
	const scrollToBottom = () => {
		setTimeout(() => {
			if (chatContainer.value) {
				chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
			}
		}, 100);
	};
	onMounted(() => {
		scrollToBottom();
	});
</script>
<style scoped>
	.chat-container::-webkit-scrollbar {
		width: 6px;
	}

	.chat-container::-webkit-scrollbar-track {
		background: transparent;
	}

	.chat-container::-webkit-scrollbar-thumb {
		background-color: rgba(156, 163, 175, 0.5);
		border-radius: 3px;
	}

	input[type="range"] {
		-webkit-appearance: none;
		width: 100%;
		height: 4px;
		border-radius: 2px;
		background: #e5e7eb;
		outline: none;
	}

	input[type="range"]::-webkit-slider-thumb {
		-webkit-appearance: none;
		appearance: none;
		width: 16px;
		height: 16px;
		border-radius: 50%;
		background: #4f46e5;
		cursor: pointer;
		transition: background .2s ease-in-out;
	}

	input[type="range"]::-webkit-slider-thumb:hover {
		background: #4338ca;
	}

	textarea:focus {
		outline: none;
		box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1);
	}

	[data-v-8aed1f8e] {
		width: 100%;
		margin: 0 auto;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10px);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes fadeOut {
		from {
			opacity: 1;
			transform: translateY(0);
		}

		to {
			opacity: 0;
			transform: translateY(10px);
		}
	}

	.animate-fade-in {
		animation: fadeIn 0.3s ease-out forwards;
	}

	.animate-fade-out {
		animation: fadeOut 0.3s ease-out forwards;
	}
</style>